package halberd.filter;

import halberd.DataType;
import halberd.ImgFilter;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;
import halberd.utils.RGBUtils;
/**
 * 
 * @author jiang
 *
 */
public class SketchFilter implements ImgFilter {
	// 高斯算子
	int[][] op = { {1, 2, 1}, {2, 4, 2}, {1, 2, 1} };
	private int deep=0;
	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		int[][][] ints = input.getDatas();
		sketch(ints, result.getDatas(), input.getWidth(), input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if (input == null) {
			return false;
		}
		DataType dt = input.getDataType();
		if (dt == DataType.GRAY) {
			return true;
		}
		return false;
	}
	private void sketch(int[][][] src, int[][][] dst, int w, int h) {
		int[][] temp2 = new int[w][h];
		// 灰度反色
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				temp2[i][j] = 255 - src[i][j][4];
			}
		}
		for (int i = 1; i < w - 1; ++i) {
			for (int j = 1; j < h - 1; ++j) {
				int R = op[0][0] * temp2[i-1][j-1] + op[0][1] * temp2[i-1][j] + op[0][2] * temp2[i-1][j+1];
				R += op[1][0] * temp2[i][j-1] + op[1][1] * temp2[i][j] + op[1][2] * temp2[i][j+1];
				R += op[2][0] * temp2[i+1][j-1] + op[2][1]* temp2[i+1][j] + op[2][2] * temp2[i+1][j+1];
				R = R / 16;
				R = RGBUtils.clamp255(R);
				temp2[i][j]= R;
			}
		}

		// 对取得高斯灰度值与 去色灰度值 进行颜色减淡混合
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				int b = temp2[i][j];
				int a = src[i][j][4];
				int c = a + a * b / (256 - b + deep);
				double ex = (c + 0.0) * c * c / 255 / 255;
				c = (int) (ex);
				c = RGBUtils.clamp255(c);
				dst[i][j][4] = c;
			}
		}
	}
}
